from django.shortcuts import render,redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model
from .models import PrivateMessage,PrivateRoom,get_room_key
# from django.db.models import Q
# from django.http import JsonResponse
User = get_user_model()
# Create your views here.


@login_required
def private_recent_rooms(req):
    rooms = PrivateRoom.objects.filter(users=req.user)
    recent_chats = []
    for room in rooms:
        other_user = room.users.exclude(id=req.user.id).first()
        if other_user:
            recent_chats.append({
                'room_key': room.key,
                'peer_username': other_user.username,
            })

    return render(req,'PrivateChat/recent_list.html',{'contacts':recent_chats})


def get_private_message(room_key):
    msg = PrivateMessage.objects.filter(key=room_key).values('sender__username','receiver__username','content','timestamp').order_by('timestamp')
    # 通过外键关系，访问关联模型的字段时，用双下划线。
    # id不需要双下划线
    return msg

@login_required
def private_room(req,room_key):
    # 这里是在最近私聊中进入私聊房间
    room = PrivateRoom.objects.filter(key=room_key).first()
    if not room:
        return redirect('PrivateChat:recent_list')
    private_message = get_private_message(room_key)
    peer_user = room.users.exclude(id=req.user.id).first()
    # 当room只有一个时 即模型对象时不需要list，是查询集时用list
    return render(req,'PrivateChat/private_room.html',{
        'room_key':room_key,
        'msg':list(private_message),
        'peer_id':peer_user.id,
        'peer_name': peer_user.username
    })

@login_required
def get_create_private_room(req,peer_id,room_id):
    # 这里是在群聊用户中建立私聊或找私聊房间并进入
    if req.user.id == peer_id:  # 不能和自己建立私聊
        return redirect('Chat:chat_room',room_id=room_id)
    key = get_room_key(req.user.id, peer_id)
    obj_user = User.objects.filter(id=peer_id).first()
    room = PrivateRoom.objects.filter(key=key).first()
    if not room:
        if obj_user:
            room = PrivateRoom.objects.create(
                key=key,
            )
            room.users.add(req.user, obj_user)
            room.save()
            return render(req, 'PrivateChat/private_room.html', {
                'room_key': key,
                'msg':'',
                'peer_id':peer_id,
                'peer_name': obj_user.username
            })
        else:
            return redirect('Chat:chat_room',room_id=room_id) # 用户不存在 返回聊天室
    private_message = get_private_message(key)
    return render(req,'PrivateChat/private_room.html',{
        'room_key':key,
        'msg': list(private_message),
        'peer_id':peer_id,
        'peer_name':obj_user.username
    })

